const { spawn } = require('child_process');
const delay = require('delay');
const path = require('path');
const fs = require('fs');
const runApplescript = require('run-applescript');
const escapeString = require('escape-string-applescript');
const vscode = require('vscode');
var config = vscode.workspace.getConfiguration('stataRun');

module.exports = {
  previousCommand: '',
  winax: null,

  send(text) {
    console.log('entering sendCode function');
    this.previousCommand = text;
    return this.sendTerminal(text)
  },
  
  sendTerminal(text) {
    let activeTermOrNull = vscode.window.activeTerminal;

    // let activeTerm = activeTermOrNull |
    if (activeTermOrNull === null || activeTermOrNull === undefined) {
      console.log("Not referencing any terminal and no terminal is open. Therefore creating new terminal.");
      activeTermOrNull = vscode.window.createTerminal("StataRun");
      activeTermOrNull.show(true);

      var cmd = config.get('vscodeTerminalBin');
      cmd += " " + text
      activeTermOrNull.sendText(cmd, true);
    }
    else {
      let activeTerm = activeTermOrNull;
      activeTerm.show(true);
      console.log(`StataRun|${text}`);
      activeTerm.sendText(text, true);
    }
  }

};
